package top.dotgo.web.base.ext;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.Projections;
import top.dotgo.kit.Const;
import top.dotgo.kit.SpringKit;
import top.dotgo.model.biz.BizDictEntity;
import top.dotgo.model.biz.QBizDictEntity;
import top.dotgo.model.biz.dto.BizDictDTO;
import top.dotgo.service.biz.IBizDictService;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jornl
 * @date 2020/3/12 11:34 星期四
 */
public class DotDict {

    private static final Map<Long, String> ALL_DICT_DM5_MAP = new HashMap<>(5);
    private static final Map<Long, List<BizDictDTO>> ALL_DICT_MAP = new HashMap<>(5);


    private DotDict() {
    }

    /**
     * 根据 公司id 加载 dict数据
     *
     * @param companyId companyId
     */
    public static void load(Long companyId) {
        QBizDictEntity qBizDictEntity = QBizDictEntity.bizDictEntity;
        Expression<?>[] expression = {qBizDictEntity.id, qBizDictEntity.key, qBizDictEntity.value, qBizDictEntity.pId};
        List<BizDictDTO> dictList = SpringKit.getBean(IBizDictService.class).findList(
                Projections.fields(BizDictEntity.class, expression),
                Collections.singletonList(qBizDictEntity.status.eq(Const.Status.dict.ENABLE.v)));
        putDict(companyId, dictList);
    }

    /**
     * 添加 公司 的 dict
     *
     * @param companyId companyId
     * @param dict      dict
     */
    public static void putDict(Long companyId, List<BizDictDTO> dict) {
        ALL_DICT_MAP.put(companyId, dict);
        ALL_DICT_DM5_MAP.put(companyId, SecureUtil.md5(JSON.toJSONString(dict)));
    }

    /**
     * 是否包含
     *
     * @param companyId companyId
     * @return true or false
     */
    public static boolean contains(Long companyId) {
        return ALL_DICT_MAP.containsKey(companyId);
    }

    /**
     * 根据公司id 获取 公司dict
     *
     * @param companyId companyId
     * @return List<BizDictEntity>
     */
    public static List<BizDictDTO> getDict(Long companyId) {
        if (!ALL_DICT_MAP.containsKey(companyId)) {
            load(companyId);
        }
        return ALL_DICT_MAP.get(companyId);
    }

    /**
     * 获取当前公司 dict的md5
     *
     * @param companyId companyId
     * @return md5
     */
    public static String getMd5(Long companyId) {
        if (ALL_DICT_DM5_MAP.containsKey(companyId)) {
            return ALL_DICT_DM5_MAP.get(companyId);
        }
        return "0";
    }

}
